﻿// Copyright (c) 2009 http://grommet.codeplex.com
// This source is subject to the Microsoft Public License.
// See http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.

using System.IO;
using System;
using Grommet.Ext;

namespace Grommet.Net.XBee
{
    public class ZigBeeTransmitStatus : ApiFrame
    {
        public ZigBeeTransmitStatus( ApiFrame frame )
        {
            this.FrameData = frame.FrameData;
            this.Callback = frame.Callback;
        }

        public byte Retries
        {
            get { return FrameData[4]; }
        }

        public DeliveryStatus DeliveryStatus
        {
            get { return (DeliveryStatus)FrameData[5]; }
        }

        public DiscoveryStatus DiscoveryStatus
        {
            get { return (DiscoveryStatus)FrameData[6]; }
        }
    }

    public class RemoteCommandResponse : ApiFrame
    {
        public RemoteCommandResponse( ApiFrame frame )
        {
            this.FrameData = frame.FrameData;
            this.Callback = frame.Callback;
        }

        public RemoteCommandStatus RemoteCommandStatus
        {
            get { return (RemoteCommandStatus)FrameData[ 14 ]; }
        }
    }

    public class ApiFrame
    {
        public const byte StartDelimiter = 0x7E;

        public XBeeCallback Callback { get; set; }

        public ushort Length 
        {
            get { return (ushort)FrameData.Length; }
        }

        public byte[] FrameData { get; set; }

        public byte Checksum
        {
            get
            {
                byte checksum = 0xFF;
                for (int i = 0; i < FrameData.Length; i++)
                {
                    checksum -= FrameData[i];
                }
                return checksum;
            }
        }

        public byte[] Serialize()
        {
            MemoryStream stream = new MemoryStream();
            stream.WriteByte(StartDelimiter);
            byte[] lengthBuffer = BigEndianConvert.GetBytes(Length);
            stream.Write(lengthBuffer, 0, lengthBuffer.Length);
            stream.Write(FrameData, 0, Length);
            stream.WriteByte(Checksum);
            stream.Close();

            return stream.ToArray();
        }

    }
}
